package com.wwk.phone.exceptionhandler;


import com.wwk.phone.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice
public class Globalexceptionhandler {

    //指定异常执行方法
    @ExceptionHandler(ArithmeticException.class)
    public R error(ArithmeticException e) {
        e.printStackTrace();
        return R.error().message("方法执行ArithmeticException异常！");
    }

    //自定义的异常处理
    @ExceptionHandler(MyException.class)
    public R error(MyException e, HttpServletRequest request) {
        log.error("Requst URL : {}，Exception : {}", request.getRequestURL(), e);

//        当标识了状态码的时候就不拦截
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        return R.error().code(e.getCode()).message(e.getMsg());
    }

}
